<?php

/**
 * mr3 actions.
 *
 * @package    student_manager
 * @subpackage mr3
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class mr3Actions extends automr3Actions
{

public function executeViewNotes(){
    $this->getResponse()->setTitle('WMS-ViewNotes-MRRaw');
    $this->mr3 = $this->getMR3OrCreate();
    $this->labels = $this->getLabels();
}
public function executeRevise(){
     $this->getResponse()->setTitle('WMS-Revise-MRRaw-Id-'.$this->getRequestParameter('id'));
    $Id = $this->getRequestParameter('id');
    $mr = MR3Peer::retrieveByPK($Id);
    if (!$mr){
        $this->getRequest()->setError('revise', 'This MR is not available!');
        $this->forward('mr3', 'list');
    }
    if ($mr->getStatus() != CommonValues::$gMRStatus['key']['In progress'] &&
            $mr->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Approved']) {
        $this->getRequest()->setError('revise', 'Could not revise this MR!');
        $this->forward('mr3', 'list');
    }
    $this->redirect('mr3/create?prepare_revise_Id='.$Id);
}

	
public function executeChangeNumber(){
      $this->getResponse()->setTitle('WMS-Change-No-MRRaw-Id-'.$this->getRequestParameter('id'));
	$id = $this->getRequestParameter('id');
    if ($this->getRequest()->isMethod('post')){    	
    	$no = $this->getRequestParameter('no');
    	if ($id && $no){
    		$obj = MR3Peer::retrieveByPK($id);
    		if ($obj){
	    		$obj->setMrno($no);
	    		$obj->save();
                        $c = new Criteria();
                        $c->add(POPeer::MRNO,$id);
                        $c->add(POPeer::COMPCATEGORY,  CommonValues::$gCompCategory['key']['Raw Material']);
                        $poList = POPeer::doSelect($c);
                        foreach ($poList as $po)
                        {
                            if ($po)
                            {
                                $po->setMrnoreal($obj->getMrno());
                                $po->Save();
                            }
                        }    
	    		$this->getUser()->setFlash('notice',  'change MR number successfully!');
	    		return $this->redirect("mr3/list?id=$id");
    		}
    	}
    }
    
    $obj = MR3Peer::retrieveByPK($id);
    $this->no = $obj->getMrno();
    $this->id = $id;
}
public function executeChangeDate()
{
    if (!$this->getUser()->hasCredential('EDIT_MRRAW'))
    {
        $this->getUser()->setFlash('notice',  'You dont have permission to edit MRRaw!');
        return $this->redirect("mr3/list?id=$id");
    }     
    $id = $this->getRequestParameter('id');     
    $obj = MR3Peer::retrieveByPK($id);
    if (!$obj)
    {
        $this->getUser()->setFlash('notice',  'MRRaw is not exist!');
        return $this->redirect("mr3/list");
    }
    if ($obj->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Approved'])
    {
        $this->getUser()->setFlash('notice',  'This MRRaw is not yet published!');
        return $this->redirect("mr3/list?id=$id");
    }    
    $this->getResponse()->setTitle('WMS-MRRaw-Change-Date-'.$obj->getMrno());
     //Lay ve Id cua Tally In  
    if ($this->getRequest()->isMethod('post'))
    { 
        //Lay ve ngay can thay doi
    	$date = $this->getRequestParameter('changedate');
    	if ($date)
        {           
            $obj->setCreatedAt($date);
            $obj->save();     
            $this->getUser()->setFlash('notice',  'Change date of '.$obj->getMrno().' successfully!');
            return $this->redirect("mr3/list?id=$id");
        }
    }
    $this->changedate = $obj->getCreatedAt();     
    $this->id = $id;
}		


public function executeView(){
      $this->getResponse()->setTitle('WMS-View-MRRaw');
    $this->mr3 = $this->getMR3OrCreate();       
    $this->labels = $this->getLabels();                 
}


  protected function addFiltersCriteria($c)
  {
    if (isset($this->filters['mrno_is_empty']))
    {
      $criterion = $c->getNewCriterion(MR3Peer::MRNO, '');
      $criterion->addOr($c->getNewCriterion(MR3Peer::MRNO, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['mrno']) && $this->filters['mrno'] !== '')
    {
      $c->add(MR3Peer::MRNO, '%'.strtr($this->filters['mrno'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['category_is_empty']))
    {
      $criterion = $c->getNewCriterion(MR3Peer::CATEGORY, '');
      $criterion->addOr($c->getNewCriterion(MR3Peer::CATEGORY, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['category']) && $this->filters['category'] !== '')
    {
      $c->add(MR3Peer::CATEGORY, $this->filters['category']);
    }
    if (isset($this->filters['reqarrdate_is_empty']))
    {
      $criterion = $c->getNewCriterion(MR3Peer::REQARRDATE, '');
      $criterion->addOr($c->getNewCriterion(MR3Peer::REQARRDATE, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['reqarrdate']))
    {
      if (isset($this->filters['reqarrdate']['from']) && $this->filters['reqarrdate']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(MR3Peer::REQARRDATE, date('Y-m-d', $this->filters['reqarrdate']['from']), Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['reqarrdate']['to']) && $this->filters['reqarrdate']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(MR3Peer::REQARRDATE, date('Y-m-d', $this->filters['reqarrdate']['to']), Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(MR3Peer::REQARRDATE, date('Y-m-d', $this->filters['reqarrdate']['to']), Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    if (isset($this->filters['created_at_is_empty']))
    {
      $criterion = $c->getNewCriterion(MR3Peer::CREATED_AT, '');
      $criterion->addOr($c->getNewCriterion(MR3Peer::CREATED_AT, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['created_at']))
    {
      if (isset($this->filters['created_at']['from']) && $this->filters['created_at']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(MR3Peer::CREATED_AT, $this->filters['created_at']['from'], Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['created_at']['to']) && $this->filters['created_at']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(MR3Peer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(MR3Peer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    if (isset($this->filters['status_is_empty']))
    {
      $criterion = $c->getNewCriterion(MR3Peer::STATUS, '');
      $criterion->addOr($c->getNewCriterion(MR3Peer::STATUS, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['status']) && $this->filters['status'] !== '')
    {
      $c->add(MR3Peer::STATUS, $this->filters['status']);
    }
    else if (isset($this->filters['status']) && $this->filters['status'] == '')
    {
      //$c->add(MR3Peer::STATUS, CommonValues::$gMRStatus['key']['Revised'], Criteria::NOT_EQUAL);
    }
    if (isset($this->filters['approvalstatus_is_empty']))
    {
      $criterion = $c->getNewCriterion(MR3Peer::APPROVALSTATUS, '');
      $criterion->addOr($c->getNewCriterion(MR3Peer::APPROVALSTATUS, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['approvalstatus']) && $this->filters['approvalstatus'] !== '')
    {
      $c->add(MR3Peer::APPROVALSTATUS, $this->filters['approvalstatus']);
    }
  }


  public function executeDelete()
  {
    $this->mr3 = MR3Peer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($this->mr3);
    
    if ($this->mr3->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Initial']
            && !$this->getUser()->hasGroup('Administrator') ){
        $this->getRequest()->setError('delete', 'Could not delete the selected MR Raw. It was published.');
        return $this->forward('mr3', 'list');
    }


    try
    {
        $MR = $this->mr3;
            $c = new Criteria();
            $c->add(POPeer::MRNO, $MR->getId());
            $c->add(POPeer::COMPCATEGORY, 2);

            $POList = POPeer::doSelect($c);

            if ($POList){
                foreach ($POList as $PO)
                {
                    $c1 = new Criteria();
                    $c1->add(TallyInPeer::TALLYNO, $PO->getId());
                    $c1->add(TallyInPeer::TYPE, CommonValues::$gTallyInType['key']['Supplier']);
                    $TIList = TallyInPeer::doSelect($c1);
                    if ($TIList)
                    {
                        foreach ($TIList as $TI)
                        {
                            $TI->delete();
                        }
                    }
                    $PO->delete();
                }
            }
      $this->deleteMR3($this->mr3);
    }
    catch (PropelException $e)
    {
      $this->getRequest()->setError('delete', 'Could not delete the selected Mr3. Make sure it does not have any associated items.');
      return $this->forward('mr3', 'list');
    }

    return $this->redirect('mr3/list');
  }

  
  
  public function executeCancel()
  {
      $id = $this->getRequestParameter('id');
      
      $mr = MR3Peer::retrieveByPK($id);
      if (!$mr) {          
            $this->getRequest()->setError('edit', 'Could not cancel this MR.');
            return $this->forward('mr3', 'list');
      }
      
      $mr->setStatus(CommonValues::$gMRStatus['key']['Cancel']);
      $mr->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Cancel']);
      $mr->save();
      
      $this->getUser()->setFlash('notice', 'This MR was canceled successfully!');
      $this->redirect('mr3/list');
  }

  
  public function executeReject()
  {
      $id = $this->getRequestParameter('id');
      $backURL = $this->getRequestParameter('backURL');
      $notes = $this->getRequestParameter('notes');
      
      $mr = MR3Peer::retrieveByPK($id);
      if (!$mr) {          
            $this->getUser()->setFlash('notice', 'Could not reject this MR because it is not available!');
            $this->redirect($backURL);
      }
      
      $mr->setStatus(CommonValues::$gMRStatus['key']['Rejected']);
      $mr->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Rejected']);
      $mr->setNotes($notes);
      $mr->save();
      
      $this->getUser()->setFlash('notice', 'This MR was rejected successfully!');
      $this->redirect($backURL);
  }
  
public function executePublish()
  {
        $id = $this->getRequestParameter('id');    
        $mr = MR3Peer::retrieveByPK($id);
        if (!$mr){
            $this->getRequest()->setError('publish', 'This MR is not available.');        
            $this->forward('mr3', 'list');
        }   
        
        if ($mr->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Initial']) {
            $this->getRequest()->setError('publish', 'This MR was published adready.');        
            $this->forward('mr3', 'list');         
        }
        
    
        $mr->setStatus(CommonValues::$gMRStatus['key']['In progress']);
        $mr->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);
        $mr->setPublishtime(time());
        
        $mr->save();
      
        //if this user have permission with PR_APPROVE_MRMAIN
        //then this MR main was consider approved one times
        if ($this->getUser()->hasCredential('PR_APPROVE_MRRAW') || $this->getUser()->hasCredential('APPROVE_MRRAW')){
            $approval = new Approval();
            $approval->setType( CommonValues::$gApprovalType['key']['MRRAW']);
            $approval->setObjectId($mr->getId());
            $approval->setUserId($this->getUser()->getGuardUser()->getId());
            $approval->save();
        }
        
        $this->getUser()->setFlash('notice', 'This MR was published successfully.');
        $this->redirect('mr3/list?id='.$id);
  }
  

public function executeList()
  {
      $this->getResponse()->setTitle('WMS-MRRaw-List');
    $this->processSort();

    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/mr3/filters');

    // pager
    $this->pager = new sfPropelPager('MR3', 25);
    $c = new Criteria();
    $c->addDescendingOrderByColumn(MR3Peer::MRNO);
    $this->addSortCriteria($c);
    $this->addFiltersCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1, 'sf_admin/mr3')));
    $this->pager->init();
    // save page
    if ($this->getRequestParameter('page')) {
        $this->getUser()->setAttribute('page', $this->getRequestParameter('page'), 'sf_admin/mr3');
    }
  }
  
         public function executeEdit()
          {
            $this->mr3 = $this->getMR3OrCreate();                   


            //revise MR
	    $reviseId = $this->getRequestParameter('prepare_revise_Id');
	    if ($reviseId != '' && $reviseId != null) {
	       $reviseMr = MR3Peer::retrieveByPK($reviseId);
	       if (!$reviseMr) {
                        $this->getRequest()->setError('edit', 'Could not revise this MR because it is not available!');
                        $this->forward('mr3', 'list');
	       }
	       $this->mr3 = $reviseMr->copy();
	       $this->mr3->setReviseId($reviseId);
	       $this->mr3->setStatus(CommonValues::$gMRStatus['key']['Initial']);
               $this->mr3->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Initial']);
	       $componentGroup = new ComponentGroup();
	       $componentGroup->setType(1);
	       $componentGroup->save();
	       $componentGroupId = $reviseMr->getComponentgroupId();
	       $c= new Criteria();
	       $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
	       $compsList = ComponentsPeer::doSelect($c);
	       foreach ($compsList  as $comps) {
	           $compsNew = $comps->copy();
	           $compsNew->setComponentId($comps->getComponentId());
	           $compsNew->setComponentgroupId($componentGroup->getId());
	           $compsNew->setQty1($comps->getQty1());
	           $compsNew->setQty2($comps->getQty2());
	           $compsNew->setQty4($comps->getQty4());
	           $compsNew->save();
	       }
	       $this->mr3->setComponentgroupId($componentGroup->getId());
	       $this->mr3->save();
	    }
            
            //check status for edit BOM
            if ($this->mr3->getStatus() != CommonValues::$gMRStatus['key']['Initial']
            && $this->mr3->getStatus() != CommonValues::$gMRStatus['key']['Cancel']
            && $this->mr3->getStatus() != CommonValues::$gMRStatus['key']['Rejected']
            ) {
                $this->getRequest()->setError('edit', 'Cannot edit this MR Raw. It was published.');
                $this->forward('mr3', 'list');
            }
        
            if ($this->getRequest()->isMethod('post'))
            {
              $this->updateMR3FromRequest();
              $this->mr3->setStatus(CommonValues::$gMRStatus['key']['Initial']);
              $this->mr3->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Initial']);
              $this->mr3->setMrno(CommonValues::GenerateAutoNumber('MR3', $this->mr3->getMrno(), 'MRRAW'));
              
              //Tien code here
              $qtys = $this->getRequestParameter('qtys');
              $rowIds = $this->getRequestParameter('rowIds');             
              
              $expdates = $this->getRequestParameter('expdates');
              
              if (isset($rowIds) && count($rowIds) && isset($qtys) && count($qtys) ) {
              	if ($this->mr3->getComponentgroupId()) {
              	    $c = new Criteria();
              	    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->mr3->getComponentgroupId());
              	    ComponentsPeer::doDelete($c);
              	}
              	$componentGroup = new ComponentGroup();
              	if ($componentGroup)    {
              		$componentGroup->setType(1);
              		$componentGroup->save();
              		$componentGroupId = $componentGroup->getId();
              		
              		if ($componentGroupId) {
              			$this->mr3->setComponentgroupId($componentGroupId);
              			for($i=0; $i < count($rowIds); $i++){
              				$components = new Components();
              				if ($components){
              					$components->setComponentgroupId($componentGroupId);
              					$components->setComponentId($rowIds[$i]);
              					$components->setQty1($qtys[$i]);
              					$components->setQty4($qtys[$i]);
                                                if ($expdates[$i]){
                                                    $components->setDate(CommonValues::ConvertDateToEN($expdates[$i]));
                                                }
              					$components->save();
              				}
              			}	      			
              		}
              	}
              }
              
              //add user id
                $this->mr3->setUserId($this->getUser()->getGuardUser()->getId());        
        
              try
              {
	              if ($this->getRequestParameter('save_as_approved'))
	              {
	              	$this->mr3->setStatus(CommonValues::$gMRStatus['key']['In progress']);
                        $this->mr3->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);
                        $this->mr3->setPublishtime(time());
				    
				    //add approval for PO
		    		$approval = new Approval();
		            $approval->setType( CommonValues::$gApprovalType['key']['MRRAW']);
		            $approval->setObjectId($this->mr3->getId());
		            $approval->setUserId(17);//support head
		            $approval->save();
		            
		            $approval = new Approval();
		            $approval->setType( CommonValues::$gApprovalType['key']['MRRAW']);
		            $approval->setObjectId($this->mr3->getId());
		            $approval->setUserId(16);//general director
		            $approval->save();
	              }
                $this->saveMR3($this->mr3);
              }
              catch (PropelException $e)
              {
                $this->getRequest()->setError('edit', 'Could not save the edited Mr3s.');
                return $this->forward('mr3', 'list');
              }

              if ($this->mr3->getReviseId()){
	           $this->getUser()->setFlash('notice',  'MR '.$this->mr3->getMrno().' was revised successfully!');
	           $this->redirect('mr3/list?id='.$this->mr3->getId());
	      }
        
              $this->getUser()->setFlash('notice', 'Your modifications have been saved');
        
              if ($this->getRequestParameter('save_as_approved'))
              {
              	return $this->redirect('mr3/list');
              }
              else if ($this->getRequestParameter('save_and_add'))
              {
                return $this->redirect('mr3/create');
              }
              else if ($this->getRequestParameter('save_and_list'))
              {
                return $this->redirect('mr3/list');
              }
              else
              {
                return $this->redirect('mr3/edit?id='.$this->mr3->getId());
              }
            }
            else
            {
              $this->labels = $this->getLabels();
            }
          }        
          
public function handleErrorEdit()
  {
    $this->preExecute();
    $this->mr3 = $this->getMR3OrCreate();
    $this->updateMR3FromRequest();

    $this->labels = $this->getLabels();
    
    //transfer data to edit_form template
    $this->mr3->qtys = $this->getRequestParameter('qtys');
    $this->mr3->expdates = $this->getRequestParameter('expdates');
    $this->mr3->rowIds = $this->getRequestParameter('rowIds');

    return sfView::SUCCESS;
  }        
  protected function getLabels()
  {
    return array(
      'mr3{id}' => 'Id:',
      'mr3{mrno}' => 'MR Number:',
      'mr3{category}' => 'Category:',
      'mr3{reqarrdate}' => 'Require Arrival Date:',
      'mr3{created_at}' => 'Request Date:',
      'mr3{status}' => 'Status:',
      'mr3{approvalstatus}' => 'Approval Status:',
      'mr3{componentgroup_id}' => 'Component List:',
      'mr3{notes}' => 'Notes:',
      'qtys' => 'Component List:',
        'expdates'=>'Date List:',
    );
  }
}
